package com.cloudlinkscm.base.authcenter.dao;

import com.cloudlinkscm.base.authcenter.constant.AccountStatusEnum;
import com.cloudlinkscm.base.authcenter.mapper.UserAccountMapper;
import com.cloudlinkscm.base.authcenter.model.UserAccount;
import com.cloudlinkscm.base.authcenter.model.dto.UserAccountSearchDTO;
import com.cloudlinkscm.base.authcenter.model.vo.UserAccountVO;
import com.cloudlinkscm.loms.framework.dao.GenericBizDao;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;

/**
 * @author : tac
 * @date : 28/07/2017
 */
@Repository
public class UserAccountDao extends GenericBizDao< UserAccount,String> {

    @Autowired
    public UserAccountDao(UserAccountMapper mapper) {
        super(mapper);
    }

    /**
     * 禁用
     */
    public int disable(String id) {
	    UserAccount userAccount = new UserAccount();
    	userAccount.setId(id);
    	userAccount.setStatus(AccountStatusEnum.STATUS_DISABLE.code);

        return updateByPrimaryKeySelective(userAccount);
    }

    /**
     * 启用
     */
    public int enable(String id) {
        return active(id);
    }

    /**
     * 激活
     */
    public int active(String id) {
	    UserAccount userAccount = new UserAccount();
	    userAccount.setStatus(AccountStatusEnum.STATUS_ACTIVE.code);
	    userAccount.setId(id);

        return updateByPrimaryKeySelective(userAccount);
    }

	/**
	 * 修改密码
	 */
	public int doChangePassword(String id, String newPassword) {
		UserAccount userAccount = new UserAccount();
		userAccount.setId(id);
		userAccount.setPassword(newPassword);

		return updateByPrimaryKeySelective(userAccount);
	}

	/**
	 * 判断是否已存在该用户名
	 */
	public boolean isExist(String username) {
		UserAccount o = new UserAccount();
		o.setAccount(username);
		return selectCount(o) > 0;
	}

	public UserAccount selectByUsername(String username){
		UserAccount o = new UserAccount();
		o.setAccount(username);
		return selectOne(o);
	}


	public UserAccountVO page(UserAccountSearchDTO searchDTO) {
		Page<UserAccount> userAccountPage = PageHelper.startPage(searchDTO.getPageIndex(), searchDTO.getPageSize(),true);
		Example example = new Example(UserAccount.class);
		example.createCriteria()
				.andLike("userId", searchDTO.getUserId())
				.andLike("account", searchDTO.getAccount())
				.andEqualTo("status", searchDTO.getStatus());

		selectByExample(example);

		UserAccountVO userAccountVO = new UserAccountVO();
		userAccountVO.setData(userAccountPage);
		userAccountVO.setReturnTotalItems(Integer.valueOf(String.valueOf(userAccountPage.getTotal())));
		return userAccountVO;
	}
}
